<template>
    <div class="physicalroom-media">
        <Loading :show="loading"></Loading>
        <div class="panel">
            <div class="panel-body">
                <MySelect
                        id="pid2"
                        v-model="pid"
                        :options="[]"
                        :searchable="true"
                        :ajax="ajaxConf"
                        minimumInputLength="2"
                        placeholder="physical_room_id"
                >
                </MySelect>
            </div>
        </div>
        <div class="panel">
            <vue2-dropzone ref="myVueDropzone3" id="myVueDropzone3" :options="dropzoneOptions"
                           @vdropzone-files-added="addedFiles"
            >
            </vue2-dropzone>
        </div>
        <div class="panel">
            <div class="panel-body">
                <draggable class="drag-wrapper" v-model="data" @update="datadragEnd" :options = "{animation:500}">
                    <transition-group>
                        <div v-for="element in data" :key="element.id" class="drag-item">
                            <div class="img-box">
                                <img :src="ossPublicURI + element.uuid" alt="">
                                <button type="button" class="delete btn btn-danger btn-circle btn-sm"
                                        @click.stop="deleteDragItem(element)"
                                >
                                    <i class="fif fif-close text-white"></i>
                                </button>
                            </div>
                        </div>
                    </transition-group>
                </draggable>
            </div>
        </div>
    </div>
</template>

<script>
    import draggable from 'vuedraggable'
    import Loading from '@/components/widgets/Loading'
    import MySelect from '@/components/widgets/MySelect'
    import {getAjaxConf} from "@/utils";
    import {searchModel, updateModel, addModel, deleteModel} from "@/api/model";
    import config from "@/config"
    import {loadMediaKey, saveMediaKey} from "@/cache";
    import vue2Dropzone from 'vue2-dropzone'
    import {getUploadInfo, uploadFileToOss, notifyFileUploadComplete} from "@/api/upload";
    import swal from "sweetalert"

    export default {
        components: {MySelect, Loading, draggable, vue2Dropzone},
        name: "PhysicalRoomMedia",
        data() {
            return {
                pid: '',
                loading: false,
                data: []
            }
        },
        watch: {
            pid() {
                saveMediaKey(this.pid)
                this.fetch()
            },
        },
        created() {
            this.originalData = [];
            this.dropzoneOptions = {
                url: 'https://httpbin.org/post',
                acceptedFiles: 'image/*',
                thumbnailWidth: 150,
                maxFilesize: 0.5,
                autoProcessQueue: false,
                addRemoveLinks: true,
                dictRemoveFile: 'X',
                resizeWidth: 100
            }
            this.files = []
            this.ajaxConf = getAjaxConf('PhysicalRoom', 'id', 'physical_room_id')
            this.ossPublicURI = config.ossPublicURI + '/resource/'
            this.pid = loadMediaKey()
            if (this.pid) {
                searchModel("PhysicalRoom", {search_keys:{id: this.pid}}).then(res => {
                    if (res.data.list.length) {
                        $("#select2-pid2-container").text(res.data.list[0].physical_room_id)
                    }
                })
            }
        },
        mounted() {
            //为了防止火狐浏览器拖拽的时候以新标签打开，此代码真实有效
            document.body.ondrop = function (event) {
                event.preventDefault();
                event.stopPropagation();
            }
        },
        methods: {
            /**
             * 请求physical_room下所有图片
             */
            fetch() {
                this.loading = true
                searchModel("PhysicalRoomMedia", {
                    search_keys: {
                        physical_room_id: this.pid,
                    },
                    order_by: "order"
                }).then(res => {
                    this.loading = false
                    this.originalData = $.extend(true,[],res.data.list) // 保存一份未被拖动前的数据，以便比较前后拖动的元素
                    this.data = res.data.list
                }).catch(e => {
                    this.loading = false
                })
            },
            // 当拖拽结束后重新更新图片排序
            datadragEnd (evt) {
                evt.preventDefault();
                this.loading = true
                // 按现有顺序，为每个元素添加新的顺序
                this.data = this.data.map((item, index) => {
                    item.order = index
                    return item
                })
                this.elNeedToUpdate()
            },
            /**
             * 找出需要更新的节点, 并为每个节点生成一个异步更新函数
             */
            elNeedToUpdate() {
                let updates = []
                let updatesFunc = []
                this.data.forEach((item, index) => {
                    if (item.id !== this.originalData[index].id || item.order !== this.originalData[index].order) {
                        updates.push({
                            id: item.id,
                            order: index
                        })
                    }
                })
                updates.forEach(item => {
                    let fn = new Promise(function (resolve, reject) {
                        updateModel('PhysicalRoomMedia', item.id, {
                            order: item.order
                        }).then(res => {
                            resolve(res)
                        }).catch(e => {
                            reject(e)
                        })
                    })
                    updatesFunc.push(fn)
                })
                Promise.all(updatesFunc).then(res => {
                    this.fetch()
                }).catch(e => this.fetch())
            },
            // 从数组中删除文件
            _removeFileArr(arr, uuid) {
                for (let i = 0; i < arr.length; i++) {
                    if (arr[i].upload.uuid === uuid) {
                        arr.splice(i, 1)
                        break;
                    }
                }
            },
            // 添加后直接上传
            addedFiles(files) {
                if (!this.pid) {
                    return this.$refs.myVueDropzone2.removeAllFiles()
                }
                this.tmpFiles = []
                for (let i = 0; i < files.length; i++) {
                    this.tmpFiles.push(files[i])
                }
                this.loading = true
                this.cloudFileIDs = []
                let cloud_file_id, uuid
                for (let i = 0; i < files.length; i++) {
                    let file = files[i]
                    getUploadInfo({
                        file_name: 'resource/' + file.name,
                        storage_type: 'PUBLIC',
                        file_size: file.size
                    }).then(res => {
                        cloud_file_id = res.data.cloud_file_id
                        uuid = res.data.upload_name.replace("resource/", "")
                        return uploadFileToOss(file, res.data)
                    }).then(res => {
                        if (cloud_file_id) {
                            return notifyFileUploadComplete({file_id: cloud_file_id})
                        } else {
                            return Promise.reject({"message": "cloud_file_id is not exist"})
                        }
                    }).then(res => {
                        this._removeFileArr(this.tmpFiles, file.upload.uuid)
                        this.cloudFileIDs.push(cloud_file_id)
                        if (uuid) {
                            return addModel("PhysicalRoomMedia", {
                                physical_room: this.pid,
                                category: "room_pic",
                                order: 999,
                                uuid: uuid,
                            })
                        } else {
                            return Promise.reject({"message": "uuid is not exist"})
                        }
                    }).then(res => {
                        this.$refs.myVueDropzone3.removeAllFiles()
                        this.fetch()
                    }).catch(e => {
                        console.log(e)
                        this.loading = false
                    })
                }
            },
            // 删除图片
            deleteDragItem(item) {
                swal({
                    title: "Are you sure?",
                    text: "Remove this item",
                    icon: "warning",
                    dangerMode: true,
                    buttons: true,
                }).then(will => {
                    if (will) {
                        deleteModel("PhysicalRoomMedia", item.id).then(res => {
                            this.fetch()
                        })
                    }
                })
            },
        }
    }
</script>

<style scoped lang="stylus">
    .physicalroom-media
        .drag-wrapper
            font-size :0;
            .drag-item
                text-align :center;
                display :inline-block;
                height :200px;
                width :50%;
                padding : 10px;
                @media (min-width :1500px)
                    width :20%;
                @media (min-width :1200px) and (max-width :1500px)
                    width :25%;
                @media (min-width :768px) and (max-width :1200px)
                    width :33.33%;
                .img-box
                    display :inline-block;
                    max-width: 100%;
                    height :100%;
                    position :relative;
                    cursor :move;
                    img
                        max-width: 100%;
                        height :100%;
                    .delete
                        cursor :pointer;
                        position :absolute;
                        right: -12px;
                        top: -12px;
                        display :none;
                        opacity :0.8;
                &:hover
                    .img-box
                        transform :translateY(-10px)
                    .delete
                        display :block;

</style>